<template>
    <div>
        <el-card>
            <el-form :inline="true" class="form">
                <el-form-item label="职位搜索" style="margin: 0;">
                    <el-input placeholder="请输入想要搜索的职位关键字" style="width: 15rem;" v-model="keyword"></el-input>
                </el-form-item>
                <el-form-item style="margin: 0;">
                    <el-button type="primary" size="default" :disabled="keyword ? false : true"
                        @click="search">搜索</el-button>
                    <el-button type="primary" size="default" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card style="margin: .625rem 0;">
            <el-button type="primary" size="default" icon="Plus" @click="addPosition"
                v-has="`btn.Role.add`">添加职位</el-button>
            <el-table style="margin: .625rem 0;" border :data="roleArr">
                <el-table-column label="#" width="80px" type="index"></el-table-column>
                <el-table-column label="id" width="80px" prop="id"></el-table-column>
                <el-table-column label="职位名称" prop="roleName"></el-table-column>
                <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip></el-table-column>
                <el-table-column label="更新时间" prop="updateTime" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" width="280px">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" icon="User" @click="setPermission(row)"
                            v-has="`btn.Role.assgin`">分配权限</el-button>
                        <el-button type="primary" size="small" icon="Edit" @click="updatePosition(row)"
                            v-has="`btn.Role.update`">编辑</el-button>
                        <el-popconfirm :title="`您确定删除${row.roleName}这个职位吗？`" width="12rem" icon="Delete"
                            @confirm="deletePosition(row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete"
                                    v-has="`btn.Role.remove`">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination :pager-count="9" v-model:current-page="pageNo" v-model:page-size="limit"
                :page-sizes="[3, 4, 5, 6]" :background="true" layout="prev, pager, next, jumper, ->, sizes, total"
                :total="total" @current-change="getHasPosition" @size-change="sizeChange" />
        </el-card>
        <el-dialog v-model="visable" :title="roleParams.id ? '更新职位' : '添加职位'">
            <el-form :model="roleParams" :rules="rules" ref="roleForm">
                <el-form-item label="职位名称" prop="roleName">
                    <el-input placeholder="请输入职位的名称" v-model="roleParams.roleName"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" size="default" @click="save">确认</el-button>
                <el-button type="primary" size="default" @click='cancel'>取消</el-button>
            </template>
        </el-dialog>
        <el-drawer v-model="drawer">
            <template #header>
                <h4>分配权限</h4>
            </template>
            <template #default>
                <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all
                    :default-checked-keys="selectArr" :props="defaultProps" />
            </template>
            <template #footer>
                <el-button type="primary" size="default" @click="save1">确认</el-button>
                <el-button type="primary" size="default" @click='cancel1'>取消</el-button>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive, onMounted, nextTick } from 'vue'
import { reqAddOrUpdateRole, reqAllRoleList, reqAllMenuList, reqSetPermission, reqDeleteRole } from '@/api/acl/role'
import type { RoleResponseData, Records, RoleData, MenuList, MenuResponseData, MenuData } from '@/api/acl/role/type'

//当前页面的页码
let pageNo = ref<number>(1)
//每一页展示的数据项数量
let limit = ref<number>(3)
//存储已有职位的总数
let total = ref<number>(0)
//储存全部职位的数据
let roleArr = ref<Records>([])
//收集用户输入的关键字
let keyword = ref<string>('')
//控制对话框的显示与隐藏
let visable = ref<boolean>(false)
//收集新增职位的数据
let roleParams = reactive<RoleData>({
    roleName: ''
})
//获取form组件实例
let roleForm = ref<any>()
//控制抽屉的显示与隐藏
let drawer = ref<boolean>(false)
//定义数组存储用户权限数据
let menuArr = ref<MenuList>([])
//一个储存权限菜单中已勾选的叶子节点的数组
let selectArr = ref<number[]>([])
//获取菜单树形控件组件的实例
let tree = ref<any>()

//获取职位信息数据
const getHasPosition = async (pager = 1) => {
    pageNo.value = pager
    let result: RoleResponseData = await reqAllRoleList(pageNo.value, limit.value, keyword.value)
    if (result.code == 200) {
        total.value = result.data.total
        roleArr.value = result.data.records
    }
}
//当下拉菜单发生变化的时候触发此方法
const sizeChange = () => {
    /*//首先让当前页码归1
    pageNo.value = 1
    */
    getHasPosition()
}
//分配权限功能过滤出已有权限的函数
const filterSelectArr = (allData: MenuList, initArr: number[]) => {
    allData.forEach((item: MenuData) => {
        if (item.children && item.children.length > 0) {
            filterSelectArr(item.children, initArr)
        }
        if (item.children && item.children.length === 0 && item.select) {
            initArr.push(item.id)
        }
    })
    return initArr
}
//分配权限按钮的回调
const setPermission = async (row: RoleData) => {
    drawer.value = true
    //收集当前要分配权限的职位的数据
    Object.assign(roleParams, row)
    //根据职位获取权限的数据
    let result: MenuResponseData = await reqAllMenuList((roleParams.id as number))
    if (result.code == 200) {
        menuArr.value = result.data
        selectArr.value = filterSelectArr(menuArr.value, [])
    }
}
//添加职位按钮的回调
const addPosition = () => {
    visable.value = true
    //清空数据
    Object.assign(roleParams, {
        id: 0,
        roleName: '',
    })
    //清空错误提示信息
    nextTick(() => {
        roleForm.value.clearValidate('roleName')
    })
}
//编辑职位按钮的回调
const updatePosition = (row: RoleData) => {
    visable.value = true
    //存储收集已有的账号信息
    Object.assign(roleParams, row)
    //清空错误提示信息
    nextTick(() => {
        roleForm.value.clearValidate('roleName')
    })
}
//删除职位按钮的回调
const deletePosition = async (id: number) => {
    let result: any = await reqDeleteRole(id)
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
        getHasPosition(roleArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}
//搜索按钮的回调
const search = () => {
    //根据关键字获取职位的相应数据
    getHasPosition()
}
//重置按钮的回调
const reset = () => {
    //清空关键字
    keyword.value = ''
    //重新加载所有数据
    getHasPosition()
}
//添加与编辑保存按钮的回调
const save = async () => {
    //表单校验结果，结果通过再发请求，没有通过则不发请求
    await roleForm.value.validate()
    visable.value = false
    let result: any = await reqAddOrUpdateRole(roleParams)
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: roleParams.id ? '更新成功' : '添加成功'
        })
        getHasPosition(roleParams.id ? pageNo.value : 1)
    } else {
        ElMessage({
            type: 'error',
            message: roleParams.id ? '更新失败' : '添加失败'
        })
    }
}
//添加与编辑取消按钮的回调
const cancel = () => {
    visable.value = false
}
//校验职位名称回调函数
const validatorRoleName = (rule: any, value: any, callback: any) => {
    if (value.trim().length > 0) {
        callback()
    } else {
        callback(new Error('职位名称不能为空'))
    }
}
//表单校验规则对象
const rules = {
    roleName: [{ require: true, trigger: 'blur', validator: validatorRoleName }]
}
//菜单树形控件的数据
const defaultProps = {
    children: 'children',
    label: 'name',
}
//分配权限功能确认按钮的回调
const save1 = async () => {
    let roleId = (roleParams.id as number)
    //选中节点的id
    let arr = tree.value.getCheckedKeys()
    //选中节点的父节点即半选节点的id
    let arr1 = tree.value.getHalfCheckedKeys()
    let permissionId = arr.concat(arr1)
    //下发权限
    let result: any = await reqSetPermission(roleId, permissionId)
    drawer.value = false
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '权限分配成功'
        })
        window.location.reload()
    } else {
        ElMessage({
            type: 'error',
            message: '权限分配失败'
        })
    }
}
//分配权限功能取消按钮的回调
const cancel1 = () => {
    visable.value = false
}

onMounted(() => {
    getHasPosition()
})
</script>

<style scoped lang="scss">
.form {
    height: 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>